import 'package:ecy_app_flutter/ecycommon/utils/EcyRandomUtil.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/exchange_user_group.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../models/exchange_card.dart';
import '../service/exchange_service.dart';
import 'EcyExchangeApplyPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/blind_box_myexchange.dart';

class EcyCardDetailPage extends StatefulWidget {
  // final ExchangeCard card;   
  
  EcyCardDetailPage({
    super.key,
    ExchangeCard? card,
    List<ExchangeUserGroup>? userGroups,
  });
  
  get card => null;

  @override
  _EcyCardDetailPageState createState() => _EcyCardDetailPageState();
}
  
class _EcyCardDetailPageState extends State<EcyCardDetailPage> {
  final ExchangeService _exchangeService = ExchangeService();
  // 添加我的卡片列表
  final List<ExchangeCard> myCards = [
    ExchangeCard(id: 1, name: "卡片1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true),
    ExchangeCard(id: 2, name: "卡片2", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)
  ];

  List<ExchangeUserGroup> userGroups = 
  [ExchangeUserGroup(userName: "userName", userAvatar: EcyRandomUtil.randomIconUrl(), 
  offerCards: [ExchangeCard(id: 0, name: "1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)], 
  wantCards: [ExchangeCard(id: 1, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true),ExchangeCard(id: 2, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)],
   canExchange: true),
   ExchangeUserGroup(userName: "userName", userAvatar: EcyRandomUtil.randomIconUrl(), 
  offerCards: [ExchangeCard(id: 0, name: "1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)], 
  wantCards: [ExchangeCard(id: 1, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true),ExchangeCard(id: 2, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)],
   canExchange: false)];
  ExchangeCard card = ExchangeCard(id: 0, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true);

  @override
  void initState() {
    super.initState();
    // _loadUserGroups();
  }

  // Future<void> _loadUserGroups() async {
  //   final groups = await _exchangeService.getUserGroups(widget.card?.id ?? 0);
  //   setState(() {
  //     userGroups = groups;
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return  ListView.builder(
        itemCount: userGroups.length,
        itemBuilder: (context, index) {
          final group = userGroups[index];
          return _buildUserExchangeGroup(group,context);
        },
      );
  }
}

String _formatExpiryTime(DateTime expiryTime) {
  final duration = expiryTime.difference(DateTime.now());
  final days = duration.inDays;
  final hours = duration.inHours % 24;
  final minutes = duration.inMinutes % 60;
  return '${days}天${hours}小时${minutes}分钟';
}





Widget _buildUserExchangeGroup(ExchangeUserGroup group, BuildContext context) {
  final List<ExchangeCard> myTestCards = [
    ExchangeCard(id: 1, name: "测试卡片1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true),
    ExchangeCard(id: 2, name: "测试卡片2", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)
  ];

  return Card(
    child: Container(
      margin: EdgeInsets.zero,
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              CircleAvatar(backgroundImage: NetworkImage(group.userAvatar)),
              SizedBox(width: 8),
              Text(group.userName, style: TextStyle(fontWeight: FontWeight.bold)),
              Spacer(),
              TextButton(
                onPressed: group.canExchange! ? () {
                  showModalBottomSheet(
                    context: context,
                    backgroundColor: Colors.transparent,
                    isScrollControlled: true,
                    builder: (context) => Container(
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
                      ),
                      child: ExchangeApplyDialog(
                        wantInCards: group.offerCards,
                        wantOutCards: group.wantCards,
                        myCards: myTestCards,
                      ),
                    ),
                  );
                } : null,
                style: TextButton.styleFrom(
                  minimumSize: Size(0, 0),
                  padding: EdgeInsets.zero,
                  fixedSize: Size(80.w, 32.w),
                  backgroundColor: group.canExchange! ? const Color(0xFFFF7BBE) : Colors.grey[300],
                  foregroundColor: Colors.white,
                  shape: const StadiumBorder(),
                ),
                child: Text(
                  '交换',
                  style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontSize: 14.w,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 12),
          // 卡片分栏
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            
            children: [
              Column(
                children: [
                  Text('TA要换出', style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
                  SizedBox(height: 4),
                  Row(
                    children: group.offerCards.map((card) => _buildCardItem(card, owned: card.owned)).toList(),
                  ),
                ],
              ),
              SizedBox(width: 32),
              Container(
                width: 1,
                height: 36,
                color: Color(0xFFD9D9D9),
                margin: EdgeInsets.only(top: 35),
              ),
              
              SizedBox(width: 32),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('TA想换入', 
                  style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
                  SizedBox(height: 4),
                  Row(
                    children: group.wantCards.map((card) => Padding(
                                                              padding: const EdgeInsets.only(right: 8.0), // 👉 每张卡片右边留 8 像素
                                                              child: _buildCardItem(card, owned: card.owned),
                                                            )
                                                          ).toList(),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    ),
  );
}

Widget _buildCardItem(ExchangeCard card, {bool owned = false}) {
  return Column(
    children: [
      // 卡片图片
      Stack(
        alignment: Alignment.center,
        children: [
          Image.network(card.imageUrl ?? EcyRandomUtil.randomIconUrl(), width: 50, height: 59),
      
          if (!owned)
            Container(
              width: 60,
              height: 60,
              alignment: Alignment.center,
              child: Text('您暂未拥有', style: TextStyle(color: Colors.white, fontSize: 10)),
              decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.5),
                            borderRadius: BorderRadius.circular(4), // 圆角半径 12
                        ),
            ),
        ]
      ),
      
        Text(card.name, style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
    ],
  );
}

class ExchangeApplyDialog extends StatefulWidget {
  final List<ExchangeCard> wantInCards;
  final List<ExchangeCard> wantOutCards;
  final List<ExchangeCard> myCards;

  const ExchangeApplyDialog({
    super.key,
    required this.wantInCards,
    required this.wantOutCards,
    required this.myCards,
  });

  @override
  State<ExchangeApplyDialog> createState() => _ExchangeApplyDialogState();
}

class _ExchangeApplyDialogState extends State<ExchangeApplyDialog> {
  ExchangeCard? selectedCard;

  void _showSuccessDialog() {
    Navigator.of(context).pop(); // 先关闭选择卡片的弹窗
    showDialog(
      context: context,
      builder: (context) => Stack(
        children: [
          Dialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
            child: Container(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    'assets/images/success_emoji.png',
                    width: 48,
                    height: 48,
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    '提交成功！',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    '您的互换申请已发送对方，可到\n"我的互换"中查看',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.grey,
                      height: 1.5,
                    ),
                  ),
                  const SizedBox(height: 24),
                  SizedBox(
                    width: double.infinity,
                    child: TextButton(
                      style: TextButton.styleFrom(
                        backgroundColor: const Color(0xFFFF7BBE),
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24),
                        ),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(); // 关闭成功弹窗
                        Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                            builder: (context) => BlindBoxMyexchange(initialTabIndex: 1),
                          ),
                        );
                      }, 
                      child: const Text('去查看'),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 180,
            child: Center(
              child: GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Container(
                  width: 36,
                  height: 36,
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: const Icon(Icons.close, color: Colors.white),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '选择想换出的商品',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
          const SizedBox(height: 16),
          // 我想换入
          const Align(
            alignment: Alignment.centerLeft,
            child: Text('我想换入', style: TextStyle(fontWeight: FontWeight.bold)),
          ),
          const SizedBox(height: 8),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: widget.wantInCards.map((card) => _buildCard(card, false)).toList(),
            ),
          ),
          const SizedBox(height: 16),
          // 我想换出
          const Align(
            alignment: Alignment.centerLeft,
            child: Text('我想换出', style: TextStyle(fontWeight: FontWeight.bold)),
          ),
          const SizedBox(height: 8),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: widget.myCards.map((card) => _buildCard(card, true)).toList(),
            ),
          ),
          const SizedBox(height: 24),
          SizedBox(
            width: double.infinity,
            child: TextButton(
              style: TextButton.styleFrom(
                backgroundColor: selectedCard != null 
                    ? const Color(0xFFFF7BBE)
                    : Colors.grey[300],
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(24),
                ),
              ),
              onPressed: selectedCard != null ? _showSuccessDialog : null,
              child: const Text(
                '申请交换',
                style: TextStyle(fontSize: 16),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCard(ExchangeCard card, bool selectable) {
    final bool isSelected = selectedCard?.id == card.id;
    
    return GestureDetector(
      onTap: selectable ? () {
        setState(() {
          selectedCard = isSelected ? null : card;
        });
      } : null,
      child: Container(
        margin: const EdgeInsets.only(right: 12),
        child: Column(
          children: [
            Container(
              decoration: BoxDecoration(
                border: Border.all(
                  color: isSelected ? const Color(0xFFFF7BBE) : Colors.grey.shade200,
                  width: isSelected ? 2 : 1,
                ),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Image.network(
                card.imageUrl ?? '',
                width: 50,
                height: 59,
                fit: BoxFit.cover,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              card.name,
              style: const TextStyle(fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }
} 